<?php

namespace app\index\controller;

use think\Controller;
use think\Db;
use think\migration\command\seed\Run;

class Service extends Controller
{
    public function index()
    {
        if (!isset($_GET['echostr'])) {
            $this->responseMsg();
        } else {
            $this->valid();
        }
    }

    //验证签名
    public function valid()
    {
        $echoStr = $_GET["echostr"];
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = 'tongchuang';
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        if ($tmpStr == $signature) {
            echo $echoStr;
            exit;
        }
    }

    //响应消息
    public function responseMsg()
    {
        //创建菜单
		
        //$this->create_menu();
		
        $postObj = simplexml_load_string(file_get_contents("php://input"), 'SimpleXMLElement', LIBXML_NOCDATA);
        $postArr = json_decode(json_encode($postObj), true);
		file_put_contents('388888.txt',print_r($postArr,true));
        if (!empty($postArr)) {
//            $this->logger("R \r\n" . $postArr);
            // $RX_TYPE = trim($postObj->MsgType);

            if ($postArr['MsgType'] == "event") {
                // 用户信息
                $user_info = $this->getUnionID31($postArr['FromUserName']);
                $user_info = json_decode($user_info, true);
				
                $openid = $user_info['openid'];        //openid
                $unionid = $user_info['unionid'];      //unionid
				//db('user')->where(['unionid'=>$unionid])->update(['app_openid'=>$openid]);
				//file_put_contents('t333333.txt', $unionid);
				$res=db('user')->where(['unionid'=>$unionid])->find();
                if($res){
                   db('user')->where(['unionid'=>$unionid])->update(['app_openid'=>$openid]); 
                }else{
                    //不存在，就先添加到用户表去
                    $data['unionid']=$unionid;
                    $data['app_openid']=$openid;
                    db('user')->insert($data);
                }
				
                if ($postArr['Event'] == 'subscribe') {
                    // 关注公众号
                    $result = $this->receiveEvent($postObj);

					// 此行代码请勿删除或修改
					// 访问印章分销系统为其新增公众号临时用户
					$this->curlCreateTmpUser($openid, $unionid);

                }

                return $result;
            }else{
				//file_put_contents('39999.txt',print_r($postArr,true));
				if($postArr['MsgType'] == "text"){
					$content=$postArr['Content'];
					$result = $this->transmitText38($postArr, $content);
				}
			}

            echo $result;
        } else {
            echo "";
            exit;
        }
    }
	
	public function ces(){
		$appid = 'wx14f0e22861952e28';//公众号appid
        $secret = '11dd50a502bdb002860bf494e1e78d72';//公众号密钥

        $access_token = json_decode(file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret),true)['access_token'];
        $url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=" . $access_token.'&type=image';
		//$url = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=" . $access_token.'&type=image';

		$data = array('media'=>new \CURLFile(ROOT_PATH .'public\uploads\20220307\3b0da93eb6ab9522fe6a11e25db5f99d.jpg'));

		
	
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_HEADER, 'image/gif');
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); //如果需要将结果直接返回到变量里，那加上这句。
		$res = curl_exec($ch);
	
		$r=json_decode(json_encode($res), true);
		$res=json_decode($r,true);
		$url123='https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token='. $access_token;
		$con=array(
			'articles'=>array(
				array(
					"thumb_media_id"=>$res['media_id'],
					"title"=>'测试印章图文',
					"content"=>"印章印章印章印章印章印章印章印章印章印章印章印章印章印章"
				),
			),
	
		);
		
		$json3=json_encode($con,JSON_UNESCAPED_UNICODE);
		$re=httpsRequest($url123,$json3);
		
		
		$es=json_decode(json_encode($re), true);
		$ess=json_decode($es,true);
		//$url456='https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token='. $access_token;
		//$con456=array(
		//		'filter'=>array(
		//			"is_to_all"=>false,
		//			"tag_id"=>2,
		//		),
		//		'mpnews'=>array(
		//			"media_id"=>$ess['media_id'],
		//		),
		//		"msgtype"=>"mpnews",
		//		"send_ignore_reprint"=>1
		//);
		
		
		
		//$json456=json_encode($con456,JSON_UNESCAPED_UNICODE);
		//$rr=httpsRequest($url456,$json456);
	
		//return $rr;
		
		

		$url789='https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token='. $access_token;
		$con789=array(
				'touser'=>array(
					"olYx_6lySQhGH8WlJzY9NWxmOb1s",
					"olYx_6r1CiYvYQLxORAEW1TpgBnc"
				),
				'mpnews'=>array(
					"media_id"=>$ess['media_id'],
				),
				"msgtype"=>"mpnews",
				"send_ignore_reprint"=>0
		);
		


		
		$json789=json_encode($con789,JSON_UNESCAPED_UNICODE);
		$ss=httpsRequest($url789,$json789);
	
		return $ss;	
		
		
	}
	
	
	    //回复文本消息
    private function transmitText38($object, $content)
    {
        if (!isset($content) || empty($content)) {
            return "";
        }
        $list=httpsRequest('http://gzh.hnwcft.com/index/Index/auto_reply');
		$list=json_decode($list,true);
        $list=$list['data'];
		//file_put_contents('39999.txt',print_r($content));
        foreach($list as $k=>$v){

            if($v['title']==$content){
                $xmlTpl = "<xml>
                    <ToUserName><![CDATA[" . $object['FromUserName'] . "]]></ToUserName>
                    <FromUserName><![CDATA[" . $object['ToUserName'] . "]]></FromUserName>
                    <CreateTime>12345678</CreateTime>
                    <MsgType><![CDATA[text]]></MsgType>
                    <Content><![CDATA[" . $v['text'] . "]]></Content>
                </xml>";
            }


        }


        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), $content);
//file_put_contents('3000.txt',print_r($result,true));
        return $result;
    }
	
	
    public function getUnionID31($openId)
    {
        $appid = 'wx14f0e22861952e28';//公众号appid
        $secret = '11dd50a502bdb002860bf494e1e78d72';//公众号密钥

        $access_token = json_decode(file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret),true)['access_token'];
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $access_token . "&openid=" . $openId . "&lang=zh_CN";

        $user_info = httpsRequest($url);

        return $user_info;
    }
    public function getUnionID($openId)
    {
		//$appid = 'wx14f0e22861952e28';//公众号appid
        //$secret = '11dd50a502bdb002860bf494e1e78d72';//公众号密钥

        //$access_token = json_decode(file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret),true)['access_token'];
        $access_token = get_access_token();
		file_put_contents('1155.txt',$access_token);
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $access_token . "&openid=" . $openId . "&lang=zh_CN";

        $user_info = httpsRequest($url);

        return $user_info;
    }

    //接收事件消息
    private function receiveEvent($object)
    {
        $content = "";
        switch ($object->Event) {
            case "subscribe":
                $content = "你好，欢迎关注同创未来！";
                break;
            case "unsubscribe":
                $content = "取消关注";
                break;
        }
		
        if (is_array($content)) {
            if (isset($content[0]['PicUrl'])) {
                $result = $this->transmitNews($object, $content);
            } else if (isset($content['MusicUrl'])) {
                $result = $this->transmitMusic($object, $content);
            }
        } else {
            $result = $this->transmitText($object, $content);
        }
        return $result;
    }

    //接收文本消息
    private function receiveText($object)
    {
        $keyword = trim($object->Content);
        //多客服人工回复模式
        if (strstr($keyword, "请问在吗") || strstr($keyword, "在线客服")) {
            $result = $this->transmitService($object);
            return $result;
        }

        /*//自动回复模式
        if (strstr($keyword, "文本")){
            $content = "这是个文本消息";
        }else if (strstr($keyword, "表情")){
            $content = "中国：".$this->bytes_to_emoji(0x1F1E8).$this->bytes_to_emoji(0x1F1F3)."\n仙人掌：".$this->bytes_to_emoji(0x1F335);
        }else if (strstr($keyword, "单图文")){
            $content = array();
            $content[] = array("Title"=>"单图文标题",  "Descri ption"=>"单图文内容", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
        }else if (strstr($keyword, "图文") || strstr($keyword, "多图文")){
            $content = array();
            $content[] = array("Title"=>"多图文1标题", "Description"=>"", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
            $content[] = array("Title"=>"多图文2标题", "Description"=>"", "PicUrl"=>"http://d.hiphotos.bdimg.com/wisegame/pic/item/f3529822720e0cf3ac9f1ada0846f21fbe09aaa3.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
            $content[] = array("Title"=>"多图文3标题", "Description"=>"", "PicUrl"=>"http://g.hiphotos.bdimg.com/wisegame/pic/item/18cb0a46f21fbe090d338acc6a600c338644adfd.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
        }else if (strstr($keyword, "音乐")){
            $content = array();
            $content = array("Title"=>"最炫民族风", "Description"=>"歌手：凤凰传奇", "MusicUrl"=>"http://121.199.4.61/music/zxmzf.mp3", "HQMusicUrl"=>"http://121.199.4.61/music/zxmzf.mp3");
        }else{
            $content = date("Y-m-d H:i:s",time())."\nOpenID：".$object->FromUserName;
        }

        if(is_array($content)){
            if (isset($content[0])){
                $result = $this->transmitNews($object, $content);
            }else if (isset($content['MusicUrl'])){
                $result = $this->transmitMusic($object, $content);
            }
        }else{
            $result = $this->transmitText($object, $content);
        }
        return $result;*/
    }

    //接收图片消息
    private function receiveImage($object)
    {
        $content = array("MediaId" => $object->MediaId);
        $result = $this->transmitImage($object, $content);
        return $result;
    }

    //接收位置消息
    private function receiveLocation($object)
    {
        $content = "你发送的是位置，经度为：" . $object->Location_Y . "；纬度为：" . $object->Location_X . "；缩放级别为：" . $object->Scale . "；位置为：" . $object->Label;
        $result = $this->transmitText($object, $content);
        return $result;
    }

    //接收语音消息
    private function receiveVoice($object)
    {
        if (isset($object->Recognition) && !empty($object->Recognition)) {
            $content = "你刚才说的是：" . $object->Recognition;
            $result = $this->transmitText($object, $content);
        } else {
            $content = array("MediaId" => $object->MediaId);
            $result = $this->transmitVoice($object, $content);
        }
        return $result;
    }

    //接收视频消息
    private function receiveVideo($object)
    {
        $content = array("MediaId" => $object->MediaId, "ThumbMediaId" => $object->ThumbMediaId, "Title" => "", "Description" => "");
        $result = $this->transmitVideo($object, $content);
        return $result;
    }

    //接收链接消息
    private function receiveLink($object)
    {
        $content = "你发送的是链接，标题为：" . $object->Title . "；内容为：" . $object->Description . "；链接地址为：" . $object->Url;
        $result = $this->transmitText($object, $content);
        return $result;
    }

    //回复文本消息
    private function transmitText($object, $content)
    {
        if (!isset($content) || empty($content)) {
            return "";
        }

        $xmlTpl = "<xml>
    <ToUserName><![CDATA[%s]]></ToUserName>
    <FromUserName><![CDATA[%s]]></FromUserName>
    <CreateTime>%s</CreateTime>
    <MsgType><![CDATA[text]]></MsgType>
    <Content><![CDATA[%s]]></Content>
</xml>";


        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), $content);

        return $result;
    }

    //回复图文消息
    private function transmitNews($object, $newsArray)
    {
        if (!is_array($newsArray)) {
            return "";
        }
        $itemTpl = "        <item>
            <Title><![CDATA[%s]]></Title>
            <Description><![CDATA[%s]]></Description>
            <PicUrl><![CDATA[%s]]></PicUrl>
            <Url><![CDATA[%s]]></Url>
        </item>
";
        $item_str = "";
        foreach ($newsArray as $item) {
            $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
        }
        $xmlTpl = "<xml>
    <ToUserName><![CDATA[%s]]></ToUserName>
    <FromUserName><![CDATA[%s]]></FromUserName>
    <CreateTime>%s</CreateTime>
    <MsgType><![CDATA[news]]></MsgType>
    <ArticleCount>%s</ArticleCount>
    <Articles>
$item_str    </Articles>
</xml>";

        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), count($newsArray));
        return $result;
    }

    //回复音乐消息
    private function transmitMusic($object, $musicArray)
    {
        if (!is_array($musicArray)) {
            return "";
        }
        $itemTpl = "<Music>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
        <MusicUrl><![CDATA[%s]]></MusicUrl>
        <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
    </Music>";

        $item_str = sprintf($itemTpl, $musicArray['Title'], $musicArray['Description'], $musicArray['MusicUrl'], $musicArray['HQMusicUrl']);

        $xmlTpl = "<xml>
    <ToUserName><![CDATA[%s]]></ToUserName>
    <FromUserName><![CDATA[%s]]></FromUserName>
    <CreateTime>%s</CreateTime>
    <MsgType><![CDATA[music]]></MsgType>
    $item_str
</xml>";

        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

    //回复图片消息
    private function transmitImage($object, $imageArray)
    {
        $itemTpl = "<Image>
        <MediaId><![CDATA[%s]]></MediaId>
    </Image>";

        $item_str = sprintf($itemTpl, $imageArray['MediaId']);

        $xmlTpl = "<xml>
    <ToUserName><![CDATA[%s]]></ToUserName>
    <FromUserName><![CDATA[%s]]></FromUserName>
    <CreateTime>%s</CreateTime>
    <MsgType><![CDATA[image]]></MsgType>
    $item_str
</xml>";

        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

    //回复语音消息
    private function transmitVoice($object, $voiceArray)
    {
        $itemTpl = "<Voice>
        <MediaId><![CDATA[%s]]></MediaId>
    </Voice>";

        $item_str = sprintf($itemTpl, $voiceArray['MediaId']);
        $xmlTpl = "<xml>
    <ToUserName><![CDATA[%s]]></ToUserName>
    <FromUserName><![CDATA[%s]]></FromUserName>
    <CreateTime>%s</CreateTime>
    <MsgType><![CDATA[voice]]></MsgType>
    $item_str
</xml>";

        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

    //回复视频消息
    private function transmitVideo($object, $videoArray)
    {
        $itemTpl = "<Video>
        <MediaId><![CDATA[%s]]></MediaId>
        <ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
    </Video>";

        $item_str = sprintf($itemTpl, $videoArray['MediaId'], $videoArray['ThumbMediaId'], $videoArray['Title'], $videoArray['Description']);

        $xmlTpl = "<xml>
    <ToUserName><![CDATA[%s]]></ToUserName>
    <FromUserName><![CDATA[%s]]></FromUserName>
    <CreateTime>%s</CreateTime>
    <MsgType><![CDATA[video]]></MsgType>
    $item_str
</xml>";

        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

    //回复多客服消息
    private function transmitService($object)
    {
        $xmlTpl = "<xml>
	<ToUserName><![CDATA[%s]]></ToUserName>
	<FromUserName><![CDATA[%s]]></FromUserName>
	<CreateTime>%s</CreateTime>
	<MsgType><![CDATA[transfer_customer_service]]></MsgType>
</xml>";

        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

    //回复第三方接口消息
    private function relayPart3($url, $rawData)
    {
        $headers = array("Content-Type: text/xml; charset=utf-8");
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $rawData);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    //字节转Emoji表情
    function bytes_to_emoji($cp)
    {
        if ($cp > 0x10000) {       # 4 bytes
            return chr(0xF0 | (($cp & 0x1C0000) >> 18)) . chr(0x80 | (($cp & 0x3F000) >> 12)) . chr(0x80 | (($cp & 0xFC0) >> 6)) . chr(0x80 | ($cp & 0x3F));
        } else if ($cp > 0x800) {   # 3 bytes
            return chr(0xE0 | (($cp & 0xF000) >> 12)) . chr(0x80 | (($cp & 0xFC0) >> 6)) . chr(0x80 | ($cp & 0x3F));
        } else if ($cp > 0x80) {    # 2 bytes
            return chr(0xC0 | (($cp & 0x7C0) >> 6)) . chr(0x80 | ($cp & 0x3F));
        } else {                    # 1 byte
            return chr($cp);
        }
    }

    //日志记录
    private function logger($log_content)
    {
        if (isset($_SERVER['HTTP_APPNAME'])) {   //SAE
            sae_set_display_errors(false);
            sae_debug($log_content);
            sae_set_display_errors(true);
        } else if ($_SERVER['REMOTE_ADDR'] != "127.0.0.1") { //LOCAL
            $max_size = 1000000;
            $log_filename = "log.xml";
            if (file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)) {
                unlink($log_filename);
            }
            file_put_contents($log_filename, date('Y-m-d H:i:s') . " " . $log_content . "\r\n", FILE_APPEND);
        }
    }

    /**
     * 创建菜单（请使用在线接口调试生成菜单）
     * url：https://mp.weixin.qq.com/debug/cgi-bin/apiinfo?t=index&type=%E8%87%AA%E5%AE%9A%E4%B9%89%E8%8F%9C%E5%8D%95&form=%E8%87%AA%E5%AE%9A%E4%B9%89%E8%8F%9C%E5%8D%95%E5%88%9B%E5%BB%BA%E6%8E%A5%E5%8F%A3%20/menu/creat
     * step1：获取access_token接口/token
     * step2：自定义菜单创建接口/menu/create
     * 注：step需要用到的body可以使用该方法中的数据：json_encode($post)
     * */
    public function create_menu38()
    {
        $access_token = get_access_token();
        
		$post = array(
			'button' => array(
				array(
					'type' => 'miniprogram',
					'name' => '商城',
					'url' => 'http://mp.weixin.qq.com',
					'appid' => 'wx4264abb79030f644',
					'pagepath' => 'pages/goodsDetail/goodsDetail'
				)
			)
		);

		$create_menu = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token=' . $access_token;

		httpsRequest($create_menu, json_encode($post, JSON_UNESCAPED_UNICODE));
    }

	function getKey()
	{
		return md5('2s0e2a1lD_amvaerakpeit' . date('Y/m/d'));
	}
	
	function getSecret()
	{
		return md5(date('Y/m/d') . '9a950aa3ef6d130d');
	}
	
	// 访问印章分销系统为其新增公众号临时用户
	function curlCreateTmpUser($gzh_openid, $unionid)
	{
		$url = 'https://zssw.hnwcft.com/Index/Auth/createTmpUser';
		$data = [
			$this->getKey() => $this->getSecret(),
			'gzh_openid' => $gzh_openid,
			'unionid' => $unionid
		];
		
		httpsRequest($url, $data);
	}


}